package network;

import java.net.DatagramPacket;

import network.Packet.packettype;

public class SpecialReceiver extends Receiver {

	Packet[] m_updatepackets;
	int m_updatesIn, m_updatesOut, m_queuedupdates;	
	public SpecialReceiver(int portnum)
	{
		super(portnum);
		m_updatesIn=0;
		m_updatesOut=0;
		m_queuedupdates=0;	
		m_updatepackets=new Packet[64];	
	}

	@Override	
	void Decode(DatagramPacket packet)
	{
		//convert byte buffer into a packet class
		//add it to the queue
		Packet p=Packet.Decode(packet);
		if (p.getType()==packettype.UPDATE||p.getType()==packettype.STATE)
		{
	
			if (p.getTimestamp()>m_timestamp)
			{
				m_timestamp=p.getTimestamp();
				m_queuedupdates++;
				m_updatepackets[m_updatesIn]=p;
				m_updatesIn++; 
				if (m_updatesIn>63)
				{
					m_updatesIn=0;
				}						
			}		
		}
		else
		{
			m_queuedpackets++;
			m_receivedpackets[m_queueIn]=p;
			m_queueIn++; 
			if (m_queueIn>63)
			{
				m_queueIn=0;
			}
		}		
		
		
	}
	
	public boolean UpdateWaiting()
	{
		if (m_updatepackets[m_updatesOut]!=null)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public Packet TakeUpdate()
	{		
		Packet p=m_updatepackets[m_updatesOut];
		m_updatepackets[m_updatesOut]=null;
		m_updatesOut++;
		if (m_updatesOut>=64)
		{
			m_updatesOut=0;
		
		}
		if (p!=null)
		{
			
		}
		m_queuedupdates--;
		return p;
	}
	
		
}
